// mplayer_player.c

#include "mplayer_player.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

// mplayer 可执行文件路径（相对于当前工作目录）
const char *mplayer_bin = "./mplayer";

pid_t play_video(const char *filename, int x, int y, int width, int height) {
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return -1;
    }

    if (pid == 0) {
        // 子进程：重定向 stdout 和 stderr 到 /dev/null，防止任何控制台输出
        int dev_null = open("/dev/null", O_WRONLY);
        if (dev_null != -1) {
            dup2(dev_null, STDOUT_FILENO);  // 屏蔽标准输出
            dup2(dev_null, STDERR_FILENO);  // 屏蔽错误输出
            close(dev_null);
        }

        // 构造参数
        char geometry[64];
        snprintf(geometry, sizeof(geometry), "%dx%d+%d+%d", width, height, x, y);

        char scale_arg[64];
        snprintf(scale_arg, sizeof(scale_arg), "scale=%d:%d", width, height);

        char *const argv[] = {
            (char *)mplayer_bin,
            "-zoom",
            "-noborder",
            "-geometry", geometry,
            "-vf", scale_arg,
            "-loop", "0",
            "-quiet",          // 静默模式
            (char *)filename,
            NULL
        };

        execv(mplayer_bin, argv);

        // 若 execv 失败，仍不会输出任何内容到控制台
        _exit(EXIT_FAILURE);
    }

    return pid;
}
